// pages/afterSalesList/afterSalesList.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //状态筛选
    option: [
      { text: '未完成', value: 0 },
      { text: '已完成', value: 1 },
      { text: '未回访', value: -1 },
      { text: '已回访', value: -2 },
      { text: '所有记录', value: -3 }
    ],
    value: -3,
    //设备维修明细
    showDetail:false,
    //处理过程详情
    afterSaleObj:{},
    //处理过程-设备编号
    detailTitle:'',
    //搜索
    searchValue:'',
    searchIds:[],
    isSearchId:false,
    //完成确认框
    showOver:false,
    //完成信息
    overDetail:null,
    //登录用户
    user:{},
    //删除确认框
    showDelete:false,
    //删除的id
    deleteId:null,
    //用户权限
    authority:null,
    //通话记录弹出层
    showCallRecord:false,
    //通话记录信息
    callRecordInfo:null,
    //平台id
    myAppId:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    this.setData({
      user: user,
      authority:app.globalData.authority,
      myAppId:app.globalData.myAppId
    })

    //查询字典-处理方式
    this.getAfterSaleMethod();

    //查询字典-故障类型
    this.getAfterSaleType();

    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let user=this.data.user;

    let param = {
      isAuth: true,
      className: 'afterSaleServiceRecord',
      data: {
        selectFields: ['equipmentObj','state','repairObj','totalPrice','departObj','processingPerson','processingTime','processingEndTime','remark','ProcessingPhone','price','logisticePrice','totalPrice','faultType','method','id','logisticsInfo','d2dStaffInfoList','expirationTime','processingPersonId','directWriter','serviceDetails','oldStore','completeDate','faultDesc','methodResult','isVisit','orderReview','confirmOrderReview'],
        sort: {
          processingTime: -1
        },
        page: {
          page: this.data.page,
          pageSize: 10
        }
      }
    }

    //按平台查询记录
    let appId=app.globalData.myAppId;
    if(appId!=3){
      if(app.globalData.afterSaleSelf){
        //是否独立售后
        param.data.appId=app.globalData.myAppId;
      }else{
        param.data.appId=[2,3,null];
      }
    }else{
      param.data.appId=[2,3,null];
    }

    //完成状态
    if(this.data.value>=0){
      param.data.state=this.data.value;
    }

    //未回访
    if(this.data.value==-1){
      param.data.state=1;
      param.data.orderReview=false;
    }

    //已回访
    if(this.data.value==-2){
      param.data.state=1;
      param.data.orderReview=true;
      param.data.confirmOrderReview=true;
    }

    //搜索
    if(this.data.isSearchId){
      param.data.equipmentId=this.data.searchIds;
    }

    let authority=this.data.authority;

    //是否可以查全部
    // if(!authority.iot.afterSales.workOrder){
    //   let complex = [{
    //     "or": {
    //       "processingPersonId": user.id,
    //       "directWriter.name": user.userName
    //       }
    //     }];
    //   param.data.complex = complex;
    // }

    CommonService.goFindList(param).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log('售后记录');
        console.log(result);

        result.forEach(item => {
          if (item.repairObj.length && item.repairObj[0].repairTime){
            item.repairTimeStr=util.timeFormat(item.repairObj[0].repairTime);
          }
          if (item.processingTime){
            item.processingTimeStr=util.timeFormat(item.processingTime);
          }
          if (item.processingEndTime){
            item.processingEndTimeStr=util.timeFormat(item.processingEndTime);
          }
          if (item.completeDate){
            item.completeDateStr=util.timeFormat(item.completeDate);
          }

          //工单到期倒计时
          if(item.expirationTime){
            item.expirationTimeStr=util.timeFormat(item.expirationTime);
            let exT=new Date(item.expirationTime).getTime();
            let currentT=new Date().getTime();
            let countdown=exT-currentT;
            if(countdown>0){
              item.countdown=(parseInt(countdown/1000/60/60));
            }else{
              item.countdown=0;
            }
          }

          //处理接待人和接单人是否可以编辑，总负责人可以编辑
          if(authority.iot.afterSales && authority.iot.afterSales.workOrder){
            item.currentUserEdit=true;
          }else{
            if(item.directWriter){
              if(item.directWriter.name==user.userName){
                item.currentUserEdit=true;
              }
            }else{
              if(item.processingPersonId==user.id){
                item.currentUserEdit=true;
              }
            }
          }

        });

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      Toast.clear();
      this.setData({
        showNothing: true
      })
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //跳转编辑
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;
    let paramObj={
      id:detail.id,
      equipmentId:detail.equipmentId,
      repairId:detail.repairObj[0].id
    }
    wx.navigateTo({
			url: "/pages/afterSalesEdit/afterSalesEdit?paramObj="+JSON.stringify(paramObj)
		})
  },

  //显示处理过程明细
  onShowDetail(e){
    let detail = e.target.dataset.detail;
    let methodMap=this.data.methodMap;
    let faultMap=this.data.faultMap;
    //console.log(detail,methodMap,faultMap);

    methodMap.forEach(function(value,key){
　　  if(key==detail.method){
        detail.methodStr=value;
      }
　　});

    faultMap.forEach(function(value,key){
　　  if(key==detail.faultType){
        detail.typeStr=value;
      }
　　});

    this.setData({
      showDetail: true,
      detailTitle:detail.equipmentObj[0].equipmentNo,
      afterSaleObj:detail
    })
  },

  //隐藏处理过程明细
  onCloseDetail(){
    this.setData({
			showDetail: false
		});
  },

  //选择状态
  onChange({detail}) {
    this.setData({
      value: detail
    })
    this.refreshListAndPage();
  },

  //显示完成确认框
  onCompleted(e){
    let detail=e.target.dataset.detail;

    //验证非空
    if(detail.faultType && detail.faultDesc && detail.method && detail.methodResult){
      this.setData({
        showOver: true,
        overDetail: detail
      })
    }else{
      Toast.fail('接待信息不完整');
    }
  },

  //隐藏完成确认框
  onCloseOver(){
    this.setData({
			showOver: false
		})
  },

  //确认完成
  confirmOver(){
    let detail = this.data.overDetail;

    let param={
      className:'afterSaleServiceRecord',
      data:{
        id: detail.id,
        state: 1,
        //处理结束时间
        processingEndTime:util.timeFormat(new Date()),
        completeDate:util.timeFormat(new Date())
      }
    }

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        this.refreshListAndPage();

        //更新报修列表中的状态
        this.updateRepair(detail.repairId,detail.equipmentId);
      }
    }).catch((error) => {
    })
  },

  //跳转物流页面
  goToLogistics(e){
    let detail = e.target.dataset.detail;

    //处理是否可编辑上门和物流配件-已完成的和非接单人都不可编辑
    let isEditWorkOrder=false;
    if(detail.currentUserEdit && detail.state==0){
      isEditWorkOrder=true;
    }

    let paramObj={
      id: detail.id,
      equipmentNo: detail.equipmentObj.length ? detail.equipmentObj[0].equipmentNo : '暂无编号',
      isEditWorkOrder: isEditWorkOrder
    }
    wx.navigateTo({
			url: "/pages/afterLogistics/afterLogistics?paramObj="+JSON.stringify(paramObj)
		})
  },

  //搜索输入时
  onChangeSearch(e){
    this.setData({
      searchValue: e.detail.value
    })

    if(!e.detail.value){
      this.setData({
        isSearchId: false
      })
    }
  },

  //点击搜索
  onSearch() {
    if(this.data.searchValue){
      //先查出设备id再查售后记录
      let param = {
        searchKey: this.data.searchValue,
        selectFields:["id"]
      }

      CommonService.goFindEquipmentList(param).then(res=>{
        let arr=[];
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          result.forEach(item => {
            arr.push(item.id);
          });
        }
        this.setData({
          isSearchId:true,
          searchIds: arr
        })
        this.refreshListAndPage();

      }).catch((error) => {
      })
    }else{
      this.setData({
        isSearchId:false
      })
      this.refreshListAndPage();
    }
  },

  //跳转上门信息
  goToVisit(e){
    let detail = e.target.dataset.detail;

    //处理是否可编辑上门和物流配件-已完成的和非接单人都不可编辑
    let isEditWorkOrder=false;
    if(detail.currentUserEdit && detail.state==0){
      isEditWorkOrder=true;
    }

    let paramObj={
      afterssrid: detail.id,
      equipmentNo: detail.equipmentObj.length ? detail.equipmentObj[0].equipmentNo : '暂无编号',
      isEditWorkOrder: isEditWorkOrder
    }
    wx.navigateTo({
			url: "/packageA/pages/afterVisitList/afterVisitList?paramObj="+JSON.stringify(paramObj)
		})
  },

  //跳转费用明细页面
  goToCost(e){
    let detail = e.target.dataset.detail;
    let paramObj={
      afterId:detail.id,
      equipmentNo:detail.equipmentObj.length ? detail.equipmentObj[0].equipmentNo : '暂无编号'
    }
    wx.navigateTo({
			url: "/packageA/pages/afterCost/afterCost?paramObj="+JSON.stringify(paramObj)
		})
  },

  //更新报修列表中的状态
  updateRepair(repairId,equipmentId){
    let param={
      className:'afterRepairRecord',
      data:{
        filter: {
          id:repairId
        },
        update: {
          set: {
            state:2
          }
        }
      }
    }

    CommonService.goUpdate(param).then(res=>{
      //查询是否还有报修
      this.lookState(equipmentId);
    }).catch((error) => {
    })
  },

  //查询是否还有报修
  lookState(equipmentId){
    let param={
      isAuth:false,
      className:'afterRepairRecord',
      data:{
        selectFields:['id'],
        equipmentId:equipmentId,
        state:{"!=":2}
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(!res.data.data.count){
        //更新设备状态
        this.updateState(equipmentId);
      }
    }).catch((error) => {
    })
  },

  //更新设备状态
  updateState(equipmentId){
    let param={
      className:'equipment',
      data:{
        filter: {
          id:equipmentId
        },
        update: {
          set: {
            state:0
          }
        }
      }
    }

    CommonService.goUpdate(param).then(res=>{
    }).catch((error) => {
    })
  },

  //查询字典-处理方式
  getAfterSaleMethod(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'processMode',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let map = new Map();

        result.forEach(item => {
          map.set(item.id,item.name);
        });

        this.setData({
          methodMap: map
        })
      }
    }).catch((error) => {
    })
  },

  //查询字典-故障类型
  getAfterSaleType(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'faultType',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let map = new Map();

        result.forEach(item => {
          map.set(item.id,item.name);
        });

        this.setData({
          faultMap: map
        })
      }
    }).catch((error) => {
    })
  },

  //跳转服务记录
  goToService(e){
    let detail=e.currentTarget.dataset.detail;
    let paramObj={
      id:detail.id,
      equipmentId:detail.equipmentId
    }
    wx.navigateTo({
			url: "/packageA/pages/afterService/afterService?paramObj="+JSON.stringify(paramObj)
		})
  },

  //显示删除确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showDelete: true,
      deleteId:detail.id
		})
  },

  //隐藏删除确认框
  onCloseDelete(){
    this.setData({
			showDelete: false
		})
  },

  //确认删除
  confirmDelete(){
    let param={
      className:"afterSaleServiceRecord",
      data:{
        id:this.data.deleteId
      }
    }

    CommonService.goDelete(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('已删除');
        //刷新列表和页码
        this.refreshListAndPage();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //点击拨打电话
  onCall(e){
    let userName=app.globalData.userInfo.userName;
    let detail=e.currentTarget.dataset.detail;
    let obj=detail.repairObj[0];

    //打电话
    wx.makePhoneCall({
      phoneNumber: obj.contact
    })

    //保存点击记录
    let callRecord=[];
    if(obj.callRecord && obj.callRecord.length){
      callRecord=obj.callRecord;
    }
    callRecord.push({
      time:util.timeFormat(new Date()),
      name:userName
    });

    //售后服务记录
    let serviceDetails=[];
    if(detail.serviceDetails && detail.serviceDetails.length){
      serviceDetails=detail.serviceDetails;
    }
    serviceDetails.push({
      content: userName + " 拨打了电话",
      datetime: util.timeFormat(new Date())
    });

    let param={
      className:'afterRepairRecord',
      data:{
        id:obj.id,
        callRecord:callRecord
      }
    }
    CommonService.goSave(param).then(res=>{
      //售后记录增加详情
      this.insertAfterDetail(detail.id,serviceDetails);
    }).catch((error) => {
    })
  },

  //显示通话记录
  onShowCallRecord(e){
    let detail=e.currentTarget.dataset.detail;
    let obj=detail.repairObj[0];

    let param={
      isAuth:false,
      className:'afterRepairRecord',
      data:{
        searchAll: true,
        id:obj.id,
        selectFields:['id','equipmentNo','repairTime','callRecord']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result.length){
        let result=res.data.data.result[0];
        if(result.callRecord && result.callRecord.length){
          this.setData({
            showCallRecord: true,
            callRecordInfo:result
          })
        }else{
          Toast.fail('暂无通话记录')
        }
      }else{
        Toast.fail('暂无通话记录')
      }
    }).catch((error) => {
      Toast.fail('暂无通话记录')
    })
  },

  //隐藏通话记录
  onCloseCallRecord(){
    this.setData({
      showCallRecord: false
    })
  },

  //跳转旧件返还
  goToReturn(e){
    let detail = e.target.dataset.detail;

    //处理是否可编辑-已完成的和非接单人都不可编辑
    let isEditWorkOrder=false;
    if(detail.currentUserEdit && detail.state==0){
      isEditWorkOrder=true;
    }

    let paramObj={
      afterssrid: detail.id,
      equipmentNo: detail.equipmentObj.length ? detail.equipmentObj[0].equipmentNo : '暂无编号',
      isEditWorkOrder: isEditWorkOrder
    }
    wx.navigateTo({
			url: "/packageA/pages/returnParts/returnParts?paramObj="+JSON.stringify(paramObj)
		})
  },

  //售后记录增加详情
  insertAfterDetail(id,arr){
    let param={
      className:'afterSaleServiceRecord',
      data:{
        id:id,
        serviceDetails:arr
      }
    }

    CommonService.goSave(param).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
